import { useRef, useState } from 'react'

export function useList(fnLoadList: Function) {
  const [list, setList] = useState<any[]>(() => [])
  const [loading, setLoading] = useState(false)
  const page = useRef(1)
  const cacheParams = useRef<Record<string, any>>({})

  const hasNext = useRef(false)

  const loadData = async (initParams: Record<string, any> = cacheParams.current, init = false) => {
    if (init) {
      page.current = 1
    }
    try {
      setLoading(true)
      const params = {
        ...initParams,
        page: {
          pageSize: 10,
          page: page.current,
        },
      }
      const res = await fnLoadList(params)

      cacheParams.current = params
      hasNext.current = res.page.hasNext

      if (page.current === 1) {
        setList(res.list)
      } else {
        setList([...list, ...res.list])
      }
    } catch (err) {
      setList([])
      console.log(err)
    }
    setLoading(false)
  }

  const loadmore = async () => {
    if (!hasNext.current) return
    page.current = page.current + 1
    loadData()
  }

  return {
    loadData,
    list,
    setList,
    page: page.current,
    loadmore,
    loading,
  }
}
